//
//  MZPlayerViewController.swift
//  HiPlayer
//
//  Created by LB on 16/7/19.
//  Copyright © 2016年 TianChaoMinZu. All rights reserved.
//

import UIKit

class MZPlayerViewController: UIViewController {
    
    var PlayerView : UIView?
    var Player : IJKMediaPlayback?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
//        let moviePath = NSBundle.mainBundle().pathForResource("keep", ofType: "mp4")!
//        let filePath = NSURL.fileURLWithPath(moviePath)
//        self.Player = IJKFFMoviePlayerController(contentURL: filePath, withOptions: nil)
        
        self.Player = IJKFFMoviePlayerController(contentURLString: "http://pull99.a8.com/live/1469071578505918.flv?ikHost=ws&ikOp=1&CodecInfo=8192", withOptions: nil)
        
        self.playView = (self.Player?.view)!
        self.PlayerView = self.disPalyView
        self.PlayerView?.backgroundColor = UIColor.blackColor()
        self.view.addSubview(self.PlayerView!)
        
        self.playView.frame = (self.PlayerView?.bounds)!
        self.playView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
        
        self.PlayerView?.insertSubview(self.playView, atIndex: 1)
        self.Player?.scalingMode = .AspectFill
        
        self.PlayerView?.addSubview(self.backBtn)
        
        //注册屏幕发生转变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MZPlayerViewController.onDeviceOrientationChange), name: UIDeviceOrientationDidChangeNotification, object: nil)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if self.Player?.isPlaying() == false {
            self.Player?.prepareToPlay()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBarHidden = false
    }
    
//    private func preferredStatusBarStyle -> barStyle : UIStatusBarStyle {
//    
//    }
    
    ///屏幕方向发生变化会调用这里.
    @objc private func onDeviceOrientationChange() {
//        let orientation = UIDevice.currentDevice().orientation
        let interfaceOrientation = UIInterfaceOrientation.Portrait
        
        switch interfaceOrientation {
        case UIInterfaceOrientation.PortraitUpsideDown:
            break
            
        case UIInterfaceOrientation.Portrait:
            UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
            self.PlayerView?.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
            break
            
        case UIInterfaceOrientation.LandscapeLeft:
            UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
            self.PlayerView?.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
            break
            
        case UIInterfaceOrientation.LandscapeRight:
            UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
            self.PlayerView?.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
            break
            
        default:
            break
        }
    }
    
    // MARK: - Install Notifiacation
    private func installMovieNotificationObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.loadStateDidChange(_:)),
                                                         name: IJKMPMoviePlayerLoadStateDidChangeNotification,
                                                         object: self.Player)
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.moviePlayBackFinish(_:)),
                                                         name: IJKMPMoviePlayerPlaybackDidFinishNotification,
                                                         object: self.Player)
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.mediaIsPreparedToPlayDidChange(_:)),
                                                         name: IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification,
                                                         object: self.Player)
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.moviePlayBackStateDidChange(_:)),
                                                         name: IJKMPMoviePlayerPlaybackStateDidChangeNotification,
                                                         object: self.Player)

    }
    
    private func removeMovieNotificationObservers() {
        NSNotificationCenter.defaultCenter().removeObserver(self,
                                                            name: IJKMPMoviePlayerLoadStateDidChangeNotification,
                                                            object: self.Player)
        NSNotificationCenter.defaultCenter().removeObserver(self,
                                                            name: IJKMPMoviePlayerPlaybackDidFinishNotification,
                                                            object: self.Player)
        NSNotificationCenter.defaultCenter().removeObserver(self,
                                                            name: IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification,
                                                            object: self.Player)
        NSNotificationCenter.defaultCenter().removeObserver(self,
                                                            name: IJKMPMoviePlayerPlaybackStateDidChangeNotification,
                                                            object: self.Player)
    }
    
    // MARK: - Selector func
    @objc private func loadStateDidChange(notify : NSNotification) {
//        let loadState : IJKMPMovieLoadState = (self.Player?.loadState)!
//        
//        if loadState != 0  && IJKMPMovieLoadState.PlaythroughOK != 0{
//            <#code#>
//        }
//        
//        
//        IJKMPMovieLoadState loadState = _player.loadState;
//        
//        if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
//            NSLog(@"LoadStateDidChange: IJKMovieLoadStatePlayThroughOK: %d\n",(int)loadState);
//        }else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
//            NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
//            [_player play];
//        } else {
//            NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
//        }
        
    }
    
    @objc private func moviePlayBackFinish(notify : NSNotification) {
//        let tempDict : NSDictionary = notify.userInfo! as NSDictionary
//        let reason = tempDict.valueForKey(IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey) as! [AnyObject]
//        
//        switch reason {
//        case IJKMPMovieFinishReason.PlaybackEnded:
//            print("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: \(reason)\n")
//            break
//        case IJKMPMovieFinishReason.UserExited:
//            print("playbackStateDidChange: IJKMPMovieFinishReasonUserExited: \(reason)\n")
//            break
//        case IJKMPMovieFinishReason.PlaybackError:
//            print("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: \(reason)\n")
//            break
//        default:
//            print("playbackPlayBackDidFinish ??? : \(reason)\n")
//            break
//        }
    }
    
    @objc private func mediaIsPreparedToPlayDidChange(notify : NSNotification) {
        print("mediaIsPrepareToPlayDidChange\n");
    }
    
    @objc private func moviePlayBackStateDidChange(notify : NSNotification) {
        
        switch self.Player!.playbackState {
        case IJKMPMoviePlaybackState.Stopped:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): stoped")
            break
        case IJKMPMoviePlaybackState.Playing:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): Playing")
            break
        case IJKMPMoviePlaybackState.Paused:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): Paused")
            break
        case IJKMPMoviePlaybackState.Interrupted:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): Interrupted")
            break
        case IJKMPMoviePlaybackState.SeekingForward:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): SeekingForward")
            break
        case IJKMPMoviePlaybackState.SeekingBackward:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): SeekingBackward")
            break
        default:
            print("IJKMPMoviePlayBackStateDidChange \(self.Player?.playbackState): Unknown")
            break
        }
    }
    
    // MARK: - Lazy
    
    //显示界面
    private lazy var disPalyView : UIView = {
        let disPalyView : UIView = UIView()
        disPalyView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
        return disPalyView
    }()
    
    //播放背景
    private lazy var playView : UIView = {
        let playView : UIView = UIView()
        return playView
    }()
    
    //退出按钮
    private lazy var backBtn : UIButton = {
        let backBtn : UIButton = UIButton(type: UIButtonType.Custom)
        backBtn.frame = CGRectMake(SCREEN_WIDTH - 60.0, SCREEN_HEIGHT - 60.0, 44.0, 44.0)
        backBtn.setTitle("关闭", forState: .Normal)
        backBtn.setTitleColor(UI_COLOR_APPNORMAL, forState: .Normal)
        backBtn.addTarget(self, action: #selector(self.exitAction), forControlEvents: UIControlEvents.TouchUpInside)
        
        return backBtn
    }()
}

extension MZPlayerViewController {
    private func setupUI() {
        self.view.backgroundColor = UIColor.whiteColor()
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBarHidden = true
    }
}

extension MZPlayerViewController {
    @objc private func exitAction() {
        self.navigationController?.popViewControllerAnimated(true)
    }
}
